package managers.messengerManager;

import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;

import managers.popupManager.PopupManager;
import utils.UserData;
import utils.UserState;

public class SpotUsersManager implements UsersManager {

	private MessengerManager manager = MessengerManager.getSharedInstance();

	public SpotUsersManager () {
	}

	private HashSet<Integer> disconnectedUsers;
	private Hashtable<Integer, UserState> onlineUsers = new Hashtable<Integer, UserState>();




	@Override
	public void updateUsers (Hashtable<Integer,UserState> onlineUsers, boolean firstUpdate) {

		disconnectedUsers = new HashSet<Integer>();
		disconnectedUsers.addAll(this.onlineUsers.keySet());

		this.onlineUsers = onlineUsers;

		doUpdate(firstUpdate);
		Iterator<Integer> it2 = disconnectedUsers.iterator();
		while (it2.hasNext()) {
			int nextUser = it2.next();
			if (nextUser == manager.getUserId())
				continue;
			UserData temp = manager.getDataManager().getUser(nextUser);
			temp.putProperty("online", false);
			System.out.println("DISCONNECTED!!!!!!!!!");
			//popup
			if (!firstUpdate)
				PopupManager.getSharedInstance().preparePopup(temp.toString(), PopupManager.INFORMATION_POPUP, "contactSignOff", null);
		}
		manager.getFeedbackManager().update();
	}


	private void doUpdate(boolean firstUpdate) {
		Enumeration<Integer> it = onlineUsers.keys();
		while (it.hasMoreElements()) {
			Integer i = it.nextElement();
			if (i == manager.getUserId())
				continue;
			UserData temp = manager.getDataManager().getUser(i);
			//popup
			if (!firstUpdate) {
				if ((Boolean) temp.getProperty("online") == false) {
					PopupManager.getSharedInstance().preparePopup(temp.toString(), PopupManager.INFORMATION_POPUP, "contactSignOn", null);
				} else {
					if (!onlineUsers.get(i).equals(temp.getProperty("state"))) {
						if (onlineUsers.get(i).equals(UserState.AVAILABLE))
							PopupManager.getSharedInstance().preparePopup(temp.toString(), PopupManager.INFORMATION_POPUP, "contactBecomesAvailable", null);
						else
							PopupManager.getSharedInstance().preparePopup(temp.toString(), PopupManager.INFORMATION_POPUP, "contactBecomesBusy", null);
					}
				}

			}
			temp.putProperty("online", true);
			temp.putProperty("state", onlineUsers.get(i));
			temp.putProperty("timestamp", Calendar.getInstance().getTime());

			disconnectedUsers.remove(i);
		}
	}

}
